namespace Cil.Ast;

public class FixedList<T> : IFixedList<T> where T : class
{
    private readonly List<T> _list = new();

    private readonly Func<T> _generator;

    public FixedList(Func<T> generator, int capacity = 0)
    {
        _generator = generator;
        ExtendToSize(capacity);
    }

    public FixedList(int capacity = 0) : this( () => default!, capacity)
    {
    }

    public static FixedList<T> Empty = new();

    public T this[int index]
    {
        get => _list[index];
        set
        {
            ExtendToSize(index);
            _list[index] = value;
        }
    }

    public int IndexOf(T item)
    {
        return _list.IndexOf(item);
    }

    public int Count => _list.Count;

    public IEnumerator<T> GetEnumerator()
    {
        return _list.Where(item => item != null).GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    private void ExtendToSize(int size)
    {
        for (var i=Count; i < size; i++)
        {
            _list.Add(_generator());
        }
    }

}